console.log('[vite] is connecting ...../')

const host = location.host

// 客户端-- 服务端建立一个通信
const socket = new WebSocket(`ws://${host}`, 'vite-hmr')

socket.addEventListener('message', async ({ data }) => {
  console.log('websocket  message event ...1111',data)
  handleMessage(JSON.parse(data))
})

async function handleMessage(payload) {
  switch (payload.type) {
    case 'connected':
      console.log('[vite] connected.....')
      setInterval(() => {
        socket.send('ping')
      }, 30000);
      break;
    case 'update':
      payload.updates.forEach(async (uptate) => {
        if (uptate.type === 'js-update') {
          const lastIndexWith = uptate.path.lastIndexOf('\\')
          const fileName = uptate.path.substring(lastIndexWith+1)
          console.log('[vite] js update',fileName)
          await import(`/target/${fileName}?t=${uptate.timestamp}`)

          // mock
          location.reload()
        }
      })
      break;
  }
}

const sheetsMap = new Map()

export function updateStyle(id, content) {
  let style = sheetsMap.get(id)
  if (!style) {
    style = document.createElement('style')
    style.setAttribute('type', 'text/css')
    style.innerHTML = content
    document.head.appendChild(style)
  } else {
    style.innerHTML = content
  }
  sheetsMap.set(id, style)
}

export function rmStyle(id) {
  const style = sheetsMap.get(id)
  if (style) {
    document.head.removeChild(style)
  }
  sheetsMap.delete(id)
}